/*
 * @# PhotoServiceImpl.java 2011-12-23 下午04:24:07
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.px.album.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ianswer.common.orm.PublicDao;
import com.ianswer.common.util.time.SecondsUtils;
import com.ianswer.px.album.entity.Photo;
import com.ianswer.px.album.redis.AlbumRedis;
import com.ianswer.px.album.redis.PhotoRedis;
import com.ianswer.px.album.service.PhotoService;

/**
 * 相片处理逻辑.
 * 
 * @author alvin hwang
 */
@Service("photoService")
public class PhotoServiceImpl implements PhotoService {

	@Resource(name = "publicDao")
	private PublicDao publicDao;

	@Override
	public List<Photo> queryAlbumPhotos(Long albumId) {
		return queryAlbumPhotos(albumId, 0);
	}
	
	@Override
	public List<Photo> queryAlbumPhotos(Long albumId, int pageIndex) {
		Photo photo = new Photo();
		photo.setAlbumId(albumId);
		photo.setPageIndex(pageIndex);
		return publicDao.query("photos.queryAlbumPhotos", photo);
	}

	@Override
	public Long insert(Photo photo) {
		photo.setCreatedAt(SecondsUtils.seconds());
		photo.setPageIndex(calPageIndex(photo.getAlbumId()));

		Long photoId = (Long) publicDao.insert("photos.insert", photo);

		AlbumRedis.incrPhotosBy(photo.getAlbumId(), 1);

		PhotoRedis.init(photo);
		
		return photoId;
	}

	private int calPageIndex(Long albumId) {
		return (AlbumRedis.photos(albumId) + 1) / RESULTS_PER_PAGE + 1;
	}
	
	@Override
	public void delete(Long albumId, Long photoId) {
		Photo photo = new Photo();
		photo.setAlbumId(albumId);
		photo.setId(photoId);

		AlbumRedis.decrPhotosBy(albumId, 1);

		publicDao.delete("photos.delete", photo);
		
		PhotoRedis.delete(photoId);
	}

	@Override
	public Photo get(Long photoId) {
		Photo cond = new Photo();
		cond.setId(photoId);
		Photo photo = publicDao.querySingle("photos.get", cond);
		
		PhotoRedis.makeup(photo);
		
		return photo;
	}

}
